<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class FsUser extends Model
{
    public $timestamps = false;

    protected $connection = 'mysql_branch';

    protected $table = 'fs_user';

    public function fsUserPhones()
    {
        return $this->hasMany('App\Models\FsUserPhone');
    }

    public function fsUserLevel()
    {
        return $this->hasOne(Level::class);
    }

    public function fsUserRemarks()
    {
        return $this->hasMany('App\Models\FsUserRemark');
    }

    public function fsUserHasIm(){
        return $this->hasOne('App\Models\FsUserHasIm');
    }

    public function userIms(){
        return $this->belongsToMany(UserIm::class,'fs_user_ims','fs_user_id','im_id');
    }

    public function phoneRecords(){
        return $this->hasMany(FsUserPhone::class);
    }
    public function phoneTwPlRecords(){
        return $this->hasMany(PhoneRecord::class);
    }

    public function cashs(){
        return $this->hasMany(Cash::class,'mem_name','username');
    }

    public function fsUserTasks(){
        return $this->hasMany(FsUserTask::class);
    }

    /**
     * @param $request
     * @param array $curr 用户id (展示当前登陆的用户信息)
     * @param string $type  导出时需要传1
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Eloquent\Builder
     */
    public function search($request,$type = '')
    {
        $builder = self::query();

        DB::connection("mysql_branch");

        $builder->selectRaw('*,(deposit_total - withdrawal_total) as profit');

        $search = $request->input('search', '');
        if ($search) {
            $like = '%' . $search . '%';
            $builder->where(function ($query) use ($like) {
                $query->where('username', 'like', $like)
                    ->orWhere('agent', 'like', $like)
                    ->orWhere('phone_num', 'like', $like)
                    ->orWhere('true_name', 'like', $like);
            });
        }
        $download = $request->input('download','');
        if($download){

        }else{
            if(!Auth::user()->hasPermissionTo('api.fsuser.index.all')){
                $carry_user_id = Auth::id();
                $task_ids = Task::where('carry_user_id',$carry_user_id)->pluck('id')->toArray();
                //导入会员的id数组
                $fs_user_id = DB::table('fs_user_tasks')->where([
                    ['carry_user_id','=',$carry_user_id],
                    ['task_id','=',null]
                ])->pluck('fs_user_id')->toArray();
                //任务添加下面的会员id
                $res = DB::table('fs_user_tasks')->whereIn('task_id',$task_ids)->pluck('fs_user_id')->toArray();
                $res = array_unique($res);
                $res = array_merge($fs_user_id,$res);
                $builder->whereIn('id', $res);
            }
        }
        //如果有查看所有会员权限才可以通过后台用户id查看他下面维护的会员
         $user_id = $request->input('user_id','');
        if($user_id){
            if(Auth::user()->hasPermissionTo('api.fsuser.index.all')){
                //有查看的权限
                $fs_user_ids = FsUserTask::where('carry_user_id',$user_id)->pluck('fs_user_id')->toArray();
                $fs_user_ids = array_unique($fs_user_ids);
                $builder->whereIn('id', $fs_user_ids);
            }
        }

        //通过主键ID筛选  1.ids[]=null  2.ids[]='1,2,3,4,5'  3.ids=[1,2,3,4,5] 4.不存在
        $ids = $request->input('ids','');
        if($ids){
            if($ids[0] == null){
                //情况1
            }elseif (isset($ids[0]) && strpos($ids[0],',')){
                //情况2
                $arr = explode(',',$ids[0]);
                $builder->whereIn('id', $arr);
            }else{
                $builder->whereIn('id', $ids);
            }
        }

        //存款总额
        $deposit_total = $request->input('deposit_total','');

        if(!empty($deposit_total[0]) && !empty($deposit_total[1])) {
            $builder->where('deposit_total', '>', $deposit_total[0]);
            $builder->where('deposit_total', '<', $deposit_total[1]);
        }elseif (!empty($deposit_total[1])){
            $builder->where('deposit_total', '<', $deposit_total[1]);
        }elseif (!empty($deposit_total[0])) {
            $builder->where('deposit_total', '>', $deposit_total[0]);
        }

        //最大存款
        $deposit_max = $request->input('deposit_max','');
        if(!empty($deposit_max[0]) && !empty($deposit_max[1])) {
            $builder->where('deposit_max', '>', $deposit_max[0]);
            $builder->where('deposit_max', '<', $deposit_max[1]);
        }elseif (!empty($deposit_max[1])){
            $builder->where('deposit_max', '<', $deposit_max[1]);
        }elseif (!empty($deposit_max[0])){
            $builder->where('deposit_max', '>', $deposit_max[0]);
        }

        //活跃会员（最后存款） date("Y-m-d H:i:s",strtotime("-3 day"))
        $last_charge_time = $request->input('last_charge_time','');
        if(!empty($last_charge_time[0]) && !empty($last_charge_time[1])){
            $builder->where('last_charge_time', '<', $last_charge_time[1]);
            $builder->where('last_charge_time', '>', $last_charge_time[0]);
        }

        //注册会员(注册时间)
        $register_time = $request->input('register_time','');
        if(!empty($register_time[0]) && !empty($register_time[1])) {
            $builder->where('register_time', '<', $register_time[1]);
            $builder->where('register_time', '>', $register_time[0]);
        }

        //提款总金额
        $withdrawal_total = $request->input('withdrawal_total','');
        if(!empty($withdrawal_total[0]) && !empty($withdrawal_total[1])) {
            $builder->where('withdrawal_total', '<', $withdrawal_total[0]);
            $builder->where('withdrawal_total', '>', $withdrawal_total[1]);
        }elseif (!empty($withdrawal_total[1])){
            $builder->where('withdrawal_total', '<', $withdrawal_total[0]);
        }elseif (!empty($withdrawal_total[0])) {
            $builder->where('withdrawal_total', '>', $withdrawal_total[1]);
        }

        //最后登录
        $last_login_time = $request->input('last_login_time','');
        if(!empty($last_login_time[0]) && !empty($last_login_time[1])) {
            $builder->where('last_login_time', '<', $last_login_time[1]);
            $builder->where('last_login_time', '>', $last_login_time[0]);
        }
        //排序
        $order = $request->input('order', '');
        if ($order) {
            // 是否是以 _asc 或者 _desc 结尾
            if (preg_match('/^(.+)_(asc|desc)$/', $order, $m)) {
                // 如果字符串的开头是这 3 个字符串之一，说明是一个合法的排序值
                if (in_array($m[1], [
                    'register_time',
                    'deposit_total',
                    'deposit_count',
                    'withdrawal_total',
                    'withdrawal_count',
                    'deposit_max',
                    'balance',
                    'last_charge_time',
                    'last_login_time',
                    'profit'
                ])) {
                    // 根据传入的排序值来构造排序参数
                    $builder->orderBy($m[1], $m[2]);
                }
            }
        }else{
            $builder->orderByDesc('register_time');
        }
        if ($type == 1) {

            return $builder;
        }
        return $builder->paginate($request->input('limit',10));
    }

    public function bookSearch($request,$ids){
        $builder = self::query();
        //加入笔记的会员ID
        if($ids){
            $builder->whereIn('id',$ids);
        }
        $search = $request->input('search', '');
        if ($search) {
            $like = '%' . $search . '%';
            $builder->where(function ($query) use ($like) {
                $query->where('username', 'like', $like)
                    ->orWhere('agent', 'like', $like)
                    ->orWhere('phone_num', 'like', $like)
                    ->orWhere('true_name', 'like', $like);
            });
        }
        //会员笔记的筛选
        $fsUserIds = $request->input('ids',[]);
        if($fsUserIds){
            $builder->whereIn('id',$fsUserIds);
        }

        return $builder->paginate($request->input('limit',10));
    }
}
